package cn.luow.freemarker.service;

import cn.luow.freemarker.model.FtlInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.ssssssss.magicapi.core.context.RequestContext;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.service.MagicResourceService;
import org.ssssssss.magicapi.modules.servlet.ResponseModule;
import org.ssssssss.script.annotation.Comment;
import org.ssssssss.script.functions.ExtensionMethod;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.StringWriter;

@Component
public class ResponseFunctionExtension implements ExtensionMethod {
    @Resource
    private MagicResourceService magicResourceService;
    @Resource
    private FreemarkerMagicDynamicRegistry freemarkerMagicDynamicRegistry;

    @Override
    public Class<?> support() {
        return ResponseModule.class;
    }

    public ResponseEntity ftl(ResponseModule response, @Comment(name="params",value="参数")Object params) throws TemplateException, IOException {
        RequestEntity entity = RequestContext.getRequestEntity();
        String path = magicResourceService.getGroupPath(entity.getApiInfo().getGroupId())+"/"+entity.getApiInfo().getPath();
        return this.ftl(response,params,"/"+path);

    }
    public ResponseEntity ftl(ResponseModule response,
                              @Comment(name="params",value="参数")Object params,
                              @Comment(name="url",value="路径")String url) throws IOException, TemplateException {
        Template template =freemarkerMagicDynamicRegistry.get(url);
        StringWriter out = new StringWriter();
        template.process(params,out);
        String html = out.toString();
        return ((ResponseEntity.BodyBuilder)ResponseEntity.ok().header("Content-Type", new String[]{"text/html;charset=utf-8"})).body(html);
    }
}
